<template>
  <el-container class="boarder">
    <el-container>
      <el-main class="main">
        <!-- 消息区域 -->
        <div class="message-area">
          <div
            v-for="(message, index) in messages"
            :key="index"
            :class="['message', message.type === 'user' ? 'message-user' : 'message-ai']"
          >
            <span v-if="message.type === 'AI'" class="role-ai">AI</span>
            <div class="message-content" v-html="formatMessage(message.text)">
            </div>
            <!-- 角色提示 -->
            <span v-if="message.type === 'user'" class="role-user">{{ username }}</span>
          </div>
        </div>
      </el-main>
      <el-footer class="foot">
        <div class="foot-content">
          <el-input v-model="input" placeholder="请输入问题" @keyup.enter="sendMessage" maxlength="100"></el-input>
          <el-button type="primary" @click="sendMessage">获取AI回复</el-button>
          <el-button type="success" @click="saveHistory">保存为历史记录</el-button>
        </div>
      </el-footer>
    </el-container>
    <el-aside class="aside">
      <div class="history-title">历史记录</div>
      <div v-if="aiStore.historyList.length === 0" class="no-history">暂无历史记录</div>
      <ul class="history-list">
        <li v-for="(history, index) in aiStore.historyList" :key="index" @click="loadHistory(history)">
          <span>{{ formatMessage(history.ask.split('\n')[0]) }}</span>
          <el-button type="danger" size="small" @click.stop="deleteHistory(history.aid)">删除</el-button>
        </li>
      </ul>
    </el-aside>
  </el-container>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useAiStore } from '@/stores/modules/ai';
import { ElMessage } from 'element-plus';

// 引入 AI Store
const aiStore = useAiStore();

// 状态变量
const input = ref('');
const messages = ref([
]);

// 用户名，从 localStorage 中获取
const username = ref('');
const router = useRouter();

// 获取用户名
onMounted(async () => {
  const user = JSON.parse(localStorage.getItem('user'));
  if (user.code) {
    try {
      username.value = user.data.name || '用户';
      await aiStore.fetchHistory(user);
    } catch (error) {
      ElMessage.error('用户名获取失败:', error);
    }
  }
});

const formatMessage = (message) => {
  // 使用正则表达式去除 <span class="hidden-think"> 标签及其内容
  let formattedMessage = message.replace(/<span class="hidden-think">.*?<\/span>/g, '');

  // 将换行符和空格转换为 HTML 格式
  formattedMessage = formattedMessage
    .replace(/\n/g, '<br>')
    .replace(/ /g, '&nbsp;');

  return formattedMessage;
};

// 发送消息
const sendMessage = async () => {
  const user = JSON.parse(localStorage.getItem('user'));

  if (!user || !user.data) {
    // 如果用户未登录，弹出未登录消息，并在2秒后跳转到登录页面
    ElMessage.error('请您先登录');
    setTimeout(() => {
      router.push('/login');
    }, 2000);
    return;
  }

  if (input.value) {
    messages.value.push({ type: 'user', text: input.value });
    await aiStore.fetchAiData(input.value);
    input.value = '';
    messages.value.push({
      type: 'AI',
      text: aiStore.aiData.answer,
    });
  }
};

// 保存历史记录
const saveHistory = async () => {
  const user = JSON.parse(localStorage.getItem('user'));
  if (!user || !user.data) {
    ElMessage.error('请您先登录');
    setTimeout(() => {
      router.push('/login');
    }, 2000);
    return;
  }
  // 生成 historyData，确保格式为 [{ ask: '', answer: '', id: '', eqid: '', faultid: '', repid: '' }]
  const historyData = [];
  let currentAsk = '';
  for (const message of messages.value) {
    const messageText = JSON.parse(JSON.stringify(message)).text;
    const messageType = JSON.parse(JSON.stringify(message)).type;
    if (messageType === 'user') {
      currentAsk = messageText;
    } else if (messageType === 'AI' && currentAsk) {
      historyData.push({
        ask: currentAsk,
        answer: messageText,
        id: user.data.id, // 用户 ID
        eqid: null, // 设备 ID
        faultid: null ,// 故障 ID
        repid: null, // 修复 ID
        pageid:1, // 页面 ID
      });
      currentAsk = '';
    }
  }
  // console.log(historyData);
  await aiStore.saveHistory(user, historyData);
};

// 需要在加载页面的时候调用一次加载历史记录，或是在保存历史记录后再次加载历史记录
const loadHistory = (history) => {//加载历史记录
  messages.value = history.ask.split('\n').map((ask, index) => ({
    type: index % 2 === 0 ? 'user' : 'AI',
    text: ask,
  }));

  const answerLines = history.answer.split('\n');
  if (answerLines.length > 0) {
    messages.value.push({
      type: 'AI',
      text: answerLines.join('\n'),
    });
  }
};
onMounted(async () => {
  const user = JSON.parse(localStorage.getItem('user'));
  if (user && user.data) {
    await aiStore.fetchHistory(user.data);
  }
});
// 删除历史记录
const deleteHistory = async (aid) => {
  try {
    await AxiosMethods.delete(`/ai/${aid}`);
    ElMessage.success('历史记录删除成功');
    const user = JSON.parse(localStorage.getItem('user'));
    if (user && user.data) {
      await aiStore.fetchHistory(user.data);
    }
  } catch (error) {
    console.error('删除历史记录失败:', error);
    ElMessage.error('删除历史记录失败');
  }
};
</script>

<style scoped>
.dashboard-container {
  display: flex;
  background-color: #f5f5f5;
}
.main {
  background-color: #f0f2f5;
  height: 80vh;
  border: #717e92 solid 1px;
  border-radius: 10px;
  position: relative;
  overflow-y: auto;
}

.message-area {
  padding: 20px;
}

.message {
  display: flex;
  margin-bottom: 10px;
  justify-content: center; /* 确保消息内容在中间，为后续调整提供基础 */
  align-items: flex-start; /* AI 和 用户消息对齐的起点 */
}

.message-user {
  justify-content: flex-end; /* 用户消息靠右 */
  align-items: flex-end; /* 用户消息靠上 */
}

.message-ai {
  justify-content: flex-start; /* AI 消息靠左 */
  align-items: flex-start; /* AI 消息靠下 */
}

.message-content {
  background-color: #f0f0f0;
  padding: 10px 15px;
  border-radius: 8px;
  font-size: 14px;
  color: #333;
  white-space: pre-wrap; /* 保留换行和空格 */
}

.message-user .message-content {
  background-color: #e0f0ff; /* 用户消息背景色 */
}

.message-ai .message-content {
  background-color: #fcffe7; /* AI 消息背景色 */
}

.message-text {
  word-break: break-word;
  margin-top: 5px;
}

.role-ai {
  display: inline-block;
  color: #333;
  margin-right: 10px;
}

.role-user {
  display: inline-block;
  color: #333;
  margin-left: 10px;
  margin-bottom: 10px;
}

.main::before {
  content: '变电站技术室出品';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  opacity: 0.2;
  font-size: 50px;
  font-weight: 300;
  color: #cccccc;
  z-index: 0;
}

.foot {
  padding: 1vh;
  background-color: #ffffff;
  border-top: 1px solid #e0e0e0;
}

.foot-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.aside {
  background-color: #ffffff;
  padding: 20px;
  border-left: 1px solid #e0e0e0;
  height: 80vh;
}

.history-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.history-list {
  list-style-type: none;
  padding: 0;
}

.history-list li {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 10px;
  border-bottom: 1px solid #e0e0e0;
  cursor: pointer;
}

.history-list li:hover {
  background-color: #f0f0f0;
}

.no-history {
  color: #999;
  text-align: center;
  margin-top: 20px;
}

.hidden-think {
  display: none; /* 隐藏 <span class="hidden-think"> 标签及其内容 */
}
</style>
